/*
 * @Author: Jim <jimjiang0909@gmail.com>
 * @Create time:   2016-11-03 10:12:42
 * @Last Modified by:   Jim
 * @Last Modified time: 2017-01-13 17:08:29
 * @File Name: photoDialog.js
 */

define(function(require, exports, module) {

    require('{base}/resources/css/photoDialog.css');
    // require('{base}/resources/css/Jcrop.min.css');
    require('{base}/resources/css/jquery-ui-1.10.3.custom.min.css');
    require('{base}/resources/css/jquery.cropzoom.css');

    var photoData = [],
        index = 0,
        photoNum = 0,
        handleType = '',
        rot = 0,
        jcropObj,
        cropzoomObj,
        photoType = 'public',
        isMyself = true,
        componentClass = 'photoDialogBox',
        tplLeft = require('{base}/tpls/photoDialogLeft.tpl'),
        tplRight = require('{base}/tpls/photoDialogRight.tpl'),
        tpl = require('{base}/tpls/photoDialog.tpl');
    var photoDialog = {
        templateLeft: _.template(tplLeft),
        templateRight: _.template(tplRight),
        template: _.template(tpl),

        render: function(obj) {
            if (typeof(obj.data) === 'undefined') {
                return;
            }
            photoData = obj.data || [];
            photoNum = obj.data.length || 0;
            handleType = obj.handleType || '';
            index = obj.index || 0;
            photoType = obj.photoType || 'public';
            isMyself = obj.isMyself || true;
            $('body').append(this.template());
            this.bindEvt();
            this.componentUpdate();
        },

        componentUpdate: function() {
            var currentData = this.getTplData();
            currentData.index = index;
            currentData.numTips = index + 1 + '/' + photoNum;
            currentData.photoType = photoType;
            currentData.handleType = handleType;
            currentData.isMyself = isMyself;
            $('.' + componentClass).find('.left').replaceWith(this.templateLeft(currentData));
            $('.' + componentClass).find('.right').replaceWith(this.templateRight(currentData));
            this.fixedDialog();
        },

        fixedDialog: function() {
            $('.' + componentClass).find('.photoDialog').imglazyload({
                startY: 0,
                endY: $('.' + componentClass).find('.photoDialog').height(),
                transform: false,
                screen: false
            });
        },

        getTplData: function() {
            var currentData = photoData[index],
                tthis = this,
                data = {
                    prof_id: Share.getUserInfo().account.usr_id,
                    pic_id: photoData[index].item_id
                };
            if (typeof(currentData.like_cnt) === 'undefined') {
                photoData[index] = $.extend(photoData[index], {
                    liked: 0,
                    comments: [],
                    like_cnt: 0,
                });
                var ajaxObj = {
                    url: seajs.data.vars.apiUrl + 'get_photo_info',
                    type: 'GET',
                    async: true,
                    data: data,
                    success: function(data) {
                        if (data) {
                            photoData[index] = $.extend(photoData[index], data);
                            tthis.componentUpdate();
                        }
                    }
                };
                $.ajax(Share.ajaxControl(ajaxObj));
            }
            return photoData[index];
        },

        bindEvt: function() {
            var tthis = this,
                Dom = $('.' + componentClass);

            Dom.find('.close').on('click', function() {
                Dom.remove();
            });

            Dom.find('.shadow').on('click', function() {
                Dom.remove();
            });

            Dom.find('.dialogArea .cancel').on('click', function(e) {
                console.log('cancel')
                Dom.find('.comfirm').css('display', 'none');
            });

            Dom.find('.dialogArea .sure').on('click', function(e) {
                tthis.sureDialog();
                Dom.find('.comfirm').css('display', 'none');
            });


            Dom.on('click', '.editPhoto', function(e) {
                rot = 0;
                handleType = 'editPhoto';
                var imgSize = Util.getNaturalSize(Dom.find('.mainPicBox img')),
                    width = 440,
                    height = 440;
                if (imgSize.width > imgSize.height) {
                    height = imgSize.height * 440 / imgSize.width;
                } else {
                    width = imgSize.width * 440 / imgSize.height;
                }
                // console.log(1111, imgSize)
                tthis.componentUpdate();
                /* Dom.find('.left img').Jcrop({
                     allowSelect: false,
                     bgFade: true,
                     bgOpacity: .3,
                     minSize: [144, 144],
                     setSelect: [0, 0, 330, 330],
                     keySupport: false,
                     // aspectRatio: 1
                 }, function() {
                     jcropObj = this;
                     jcropObj.setOptions({ aspectRatio: 1 });
                 });*/
                cropzoomObj = Dom.find('.rotatePhoto').cropzoom({
                    // width: 600,
                    // height: 400,
                    bgColor: '#CCC',
                    // enableRotation: true,
                    // enableZoom: true,
                    // zoomSteps: 10,
                    // rotationSteps: 10,
                    selector: {
                        w: 144,
                        h: 144,
                        maxWidth: 330,
                        centered: true,
                        aspectRatio: true,
                        showPositionsOnDrag: false,
                        showDimetionsOnDrag: false,
                        bgInfoLayer: '#fff',
                        borderColor: 'blue',
                        borderColorHover: 'yellow'
                    },
                    image: {
                        source: photoData[index].picture,
                        width: width,
                        height: height,
                        minZoom: 50,
                        maxZoom: 150
                    }
                });
            });

            Dom.on('click', '.arrowLeft', function() {
                tthis.leftMove();
            });

            Dom.on('click', '.arrowRight', function() {
                tthis.rightMove();
            });

            Dom.on('click', '.mainPhoto', function(e) {
                handleType = 'mainPhoto';
                tthis.showDialog('Set it as main photo?');
            });

            Dom.on('click', '.movePhoto', function(e) {
                handleType = 'movePhoto';
                var text = photoType == 'public' ? 'Move this photo to private album?' : 'Move this photo to public album?';
                tthis.showDialog(text);
            });

            Dom.on('click', '.deletePhoto', function(e) {
                handleType = 'deletePhoto';
                tthis.showDialog('Are you sure you want to delete this photo?');
            });

            Dom.on('click', '.boxFlag', function(e) {
                tthis.flagPhoto(touch, opts.data);
            });

            Dom.on('keyup', '.description', function() {
                var buttonDom = Dom.find('.save');
                if ($.trim($(this).val()).length > 0) {
                    buttonDom.addClass('buttonColor');
                } else {
                    if (buttonDom.hasClass('buttonColor')) {
                        buttonDom.removeClass('buttonColor');
                    }
                }
            });

            Dom.on('click', '.save', function() {
                var about = $.trim(Dom.find('.description').val());
                if ($(this).hasClass('buttonColor') && about.length > 0) {
                    tthis.editPhotoDesc(about);
                } else {
                    return;
                }
            });

            Dom.on('click', '.cancel', function() {
                Dom.find('.save').removeClass('buttonColor');
                Dom.find('.description').val('');
            });

            Dom.on('click', '.photoLikes a', function() {
                console.log(1234)
            });
            /*
            Dom.on('click', '.rotateLeft', function() {
                console.log('rotateLeft');
                rot -= 90;
                rot = rot == -360 ? 0 : rot;
                // var imgSrc = seajs.data.vars.apiAccessUrl + 'show_rotated_pic_?usr_id=' + _entrance.g_userData.usr_id + '&pic_id=' + This.g_imgId + '&angle=' + This.rot;
                // Dom.find('.editImg').attr('src', );
                Dom.find('.editImg').css({ 'transform': 'rotate(' + rot + 'deg)', display: 'inline-block' });
                Dom.find('.jcrop-holder img').css({ 'transform': 'rotate(' + rot + 'deg)', display: 'inline-block' });
                // Dom.find('.editImg').css({ 'transform': 'rotate(' + rot + 'deg)' });
                // jcropObj.destroy();
                // tthis.componentUpdate();
                 Dom.find('.editImg').Jcrop({
                     allowSelect: false,
                     bgFade: true,
                     bgOpacity: .3,
                     minSize: [144, 144],
                     setSelect: [0, 0, 330, 330],
                     keySupport: false,
                     // aspectRatio: 1
                 }, function() {
                     jcropObj = this;
                     jcropObj.setOptions({ aspectRatio: 1 });
                 });
                 Dom.find('.jcrop-holder img').css({ 'transform': 'rotate(90deg)' });
            });

            Dom.on('click', '.rotateRight', function() {
                rot += 90;
                rot = rot == 360 ? 0 : rot;
                // var imgSrc = seajs.data.vars.apiAccessUrl + 'show_rotated_pic_?usr_id=' + _entrance.g_userData.usr_id + '&pic_id=' + This.g_imgId + '&angle=' + This.rot;
                // Dom.find('.editImg').attr('src', );
                Dom.find('.editImg').css({ 'transform': 'rotate(' + rot + 'deg)', display: 'inline-block' });
                jcropObj.destroy();
            });*/

            Dom.on('click', '.editBtn button', function() {
                // console.log('rotate_photo')
                cropzoomObj.send(seajs.data.vars.apiAccessUrl + 'rotate_photo', 'POST', { picno: index, changed: 1, only_extra_picture: photoType == 'public' ? 0 : 1, pic_id: photoData[index].item_id }, function(result) {
                    // console.log(111, rta);
                    if (result.results == 1) {
                        photoData[index] = $.extend(photoData[index], result.data, { active: 0 });
                        console.log(123, photoData[index])
                        tthis.updateUserInfo(photoType == 'public' ? 'changePub' : 'changePri', tthis.handleData(photoData));
                        Dom.remove();
                    }
                });

            })
        },

        showDialog: function(text) {
            $('.' + componentClass).find('.comfirm').css('display', 'block').find('.sliderText').html(text);
        },

        sureDialog: function() {
            switch (handleType) {
                case 'mainPhoto':
                    this.mainPhoto();
                    break;
                case 'movePhoto':
                    this.movePhoto();
                    break;
                case 'deletePhoto':
                    this.deletePhoto();
                    break;
                default:
                    break;
            }
        },

        editPhotoDesc: function(about) {
            var tthis = this,
                data = { item_id: photoData[index].item_id, private: photoType == 'public' ? 0 : 1, about: about },
                obj = {
                    url: seajs.data.vars.apiAccessUrl + 'edit_photo',
                    type: 'POST',
                    data: data,
                    success: function(data) {
                        if (parseInt(data.results) == 1) {
                            photoData[index].desc = data.about;
                            tthis.updateUserInfo(photoType == 'public' ? 'changePub' : 'changePri', tthis.handleData(photoData));
                        } else {
                            alert(data.msg);
                        }
                    },
                    error: function(xhr, errorType, error) {},
                    complete: function(xhr, status) {}
                };
            $.ajax(Share.ajaxControl(obj));

        },

        movePhoto: function() {
            var tthis = this,
                data = { item_id: photoData[index].item_id, action: photoType == 'public' ? 'to_extra' : 'to_pub', album_type: photoType == 'public' ? 11 : -1 },
                obj = {
                    url: seajs.data.vars.apiAccessUrl + 'move_photo',
                    type: 'POST',
                    data: data,
                    success: function(data) {
                        if (data.errcode == 123) {
                            alert(data.errmsg);
                        } else {
                            var userInfo = Share.getUserInfo();
                            var pictures = userInfo.pictures,
                                private_pictures = userInfo.private_pictures;
                            if (photoType == 'public') {
                                private_pictures.push(pictures[index]);
                                pictures.splice(index, 1);
                            } else {
                                pictures.push(private_pictures[index]);
                                private_pictures.splice(index, 1);
                            }
                            photoData.splice(index, 1);
                            photoNum -= 1;
                            index = index >= photoNum ? index - 1 : index;
                            tthis.updateUserInfo('move', { pictures: pictures, private_pictures: private_pictures });
                            tthis.componentUpdate();
                        }
                    },
                    error: function(xhr, errorType, error) {}
                };
            $.ajax(Share.ajaxControl(obj));
        },

        mainPhoto: function() {
            var tthis = this,
                from_id = photoData[index].item_id,
                to_id = photoData[0].item_id,
                type = (photoType == 'public') ? 0 : 1;
            var obj = {
                url: seajs.data.vars.apiAccessUrl + 'set_photo_order',
                type: 'POST',
                data: { 'from_id': from_id, 'to_id': to_id, 'private': type },
                success: function(data) {
                    if (data.errcode == 121) {
                        alert(data.errmsg);
                    } else {
                        [photoData[0], photoData[index]] = [photoData[index], photoData[0]];
                        index = 0;
                        tthis.updateUserInfo('main', { photo: tthis.handleData([photoData[0]])[0], pictures: tthis.handleData(photoData) });
                        tthis.componentUpdate();
                    }
                },
                error: function(xhr, errorType, error) {}
            };
            $.ajax(Share.ajaxControl(obj));
        },

        deletePhoto: function() {
            var type = photoType == 'public' ? 0 : 1;
            var tthis = this,
                obj = {
                    url: seajs.data.vars.apiAccessUrl + 'delete_photo',
                    type: 'POST',
                    data: { 'item_id': photoData[index].item_id, 'private': type },
                    success: function(data) {
                        if (data.errcode == 121) {
                            alert(data.errmsg);
                        } else {
                            photoData.splice(index, 1);
                            photoNum -= 1;
                            index = index >= photoNum ? index - 1 : index;
                            tthis.updateUserInfo(photoType == 'public' ? 'changePub' : 'changePri', tthis.handleData(photoData));
                            tthis.componentUpdate();
                        }
                    },
                    error: function(xhr, errorType, error) {}
                };
            $.ajax(Share.ajaxControl(obj));

        },

        rightMove: function(currentSlider) {
            if (index < photoNum - 1) {
                index += 1;
            } else {
                alert('This picture is the last one');
                return;
            }
            this.componentUpdate();
        },

        leftMove: function(currentSlider) {
            if (index == 0) {
                alert('This picture is the first one.');
                return;
            } else {
                index -= 1;
            }
            this.componentUpdate();
        },

        handleData: function(data) {
            var tmp = [];
            for (var i in data) {
                tmp[i] = data[i];
                delete tmp[i].liked;
                delete tmp[i].comments;
                delete tmp[i].like_cnt;
                delete tmp[i].index;
                delete tmp[i].numTips;
                delete tmp[i].photoType;
            }
            return tmp;
        },

        updateUserInfo: function(type, obj) {
            var data = Share.getUserInfo();
            switch (type) {
                case 'changePub':
                    data.pictures = obj;
                    break;
                case 'changePri':
                    data.private_pictures = obj;
                    break;
                case 'move':
                    data.pictures = obj.pictures;
                    data.private_pictures = obj.private_pictures;
                    break;
                case 'main':
                    data.photo = obj.photo;
                    data.pictures = obj.pictures;
                    break;
            }
            Util.setSessionStorage('userInfo', JSON.stringify(data));
        },

    };
    module.exports = photoDialog;

});
